<?php
namespace app\Home\controller;

//引入框架的控制器
use think\Controller;

//引入验证码
use think\captcha\Captcha;

//引入Cookie
use think\Cookie;

use think\Db;

class Index extends Controller
{
    //构造函数
    public function __construct(){
        //手动把父类的方法获取过来
        parent::__construct();

        //在控制器的全局中保留一个全局变量
        //app/common/Model/User/User.php
        $this->UserModel = model('User.User');
        $this->ConfigModel = model('Config');
        $this->PostModel = model('Post.Post');
        $this->CommentModel = model('Post.Comment');

        $SystemList = $this->ConfigModel->select();

        $System = [];
        
        foreach($SystemList as $item){
            // SystemList（配置表）key当数组key
            $System[$item['key']] = $item['value'];
        }
        //让每个界面都可以获取系统配置
        $this->assign('System', $System);
    }

    // 首页页面
    public function index()
    {
        // 分类ID
        $cateid = $this->request->param('cateid', 0);

        // 帖子热度（置顶，精华，热门）
        $state = $this->request->param('state', 0);

        // 帖子状态（全部，未结，已结）
        $accept = $this->request->param('accept', 2);

        // 关键字
        $keywords = $this->request->param('keywords', '');

        //查询分类列表
        $catelist = model('Post.Cate')->order('id asc')->limit(6)->select();

        $where = [];

        if($cateid){
            $where['cateid']  = $cateid ;
        }

        if($state){
            $where['state'] = $state;
        }

        if($accept < 2){
            // 未结
            if($accept == 0){
                $where['accept'] = ['exp', Db::raw("is null")];
            } else{
                $where['accept'] = ['exp', Db::raw("is not null")];
            }
        }

        // 关键字查询条件
        if($keywords){
            $where['title|post.content'] = [['like',"%$keywords%"], "OR"];
        }

        //分页数据查询  如果使用关联预查询功能，对于一对一关联来说，只有一次查询，对于一对多关联的话，就可以变成2次查询，有效提高性能 with([**,**])

        //查询帖子  paginate(10)每页显示10条数据
        $postlist = $this->PostModel->with(['cate','user'])->where($where)->order('createtime','desc')->paginate(10);

        // echo $this->PostModel->getLastSql();
        // exit;
        
        // 获取分页显示
        $pagestr = $postlist->render();

        // var_dump($postlist);
        // exit;
        $this->assign([
            'catelist' => $catelist,
            'cateid' => $cateid,
            'pagestr' => $pagestr,
            'postlist' => $postlist,
            'accept' => $accept,
            'state' => $state
        ]);

        return $this->fetch();
    }

    // 登陆页面
    public function login()
    {
        if($this->request->isPost()){
            $params = $this->request->param();
            $code = $this->request->param('vercode', '');
            $password = $this->request->param('password', '');
            //判断验证码是否正确 如果结果返回true就是正确否则失败
            if(!captcha_check($code)){
                //验证失败
                $this->error('验证码输入错误');
                exit;
            }
            $userinfo = $this->UserModel->where(['email' => $params['email']])->find();
            if(!$userinfo){
                $this->error('该用户不存，请注册');
                exit;
            }

            // 校验密码是否正确
            $password = md5($password.$userinfo['salt']);

            if($password != $userinfo['password']){
                $this->error('密码错误，请重新输入');
                exit;
            }

            $data =[
                'id' => $userinfo['id'],
                'nickname' => $userinfo['nickname'],
                'sex'=>$userinfo['sex'],
                'content'=>$userinfo['content'],
                'avatar'=>is_file($userinfo['avatar']) ? '/'.$userinfo['avatar'] : '/assets/home/images/avatar.jpg',
                'cover'=>is_file($userinfo['cover']) ? '/'.$userinfo['cover'] : '/assets/home/images/back.jpg',
                'auth'=>$userinfo['auth'],
                'vip'=>$userinfo['vip']
            ];

            Cookie::set('LoginUser', $data);
           
            //注册成功，跳转到登录界面
            $this->success('登陆成功',url('home/index/index'));
            exit;
            
        }
        return $this->fetch();
    }

    // 注册页面
    public function register()
    {
        // request 请求函数，isPost：判断是POST请求  param()获取请求的参数
        if($this->request->isPost()){

            $params = $this->request->param();
            $code = $this->request->param('code', '');
            $password = $this->request->param('password', '');
            $repass = $this->request->param('repass', '');

            //判断验证码是否正确 如果结果返回true就是正确否则失败
            if(!captcha_check($code)){
                //验证失败
                $this->error('验证码输入错误');
                exit;
            }

            // 校验密码是否一致
            if($password != $repass){
                $this->error('密码不一致，请重新输入');
                exit;
            }

            //生成密码盐
            $salt = randstr(10);

            // 密码加密
            $password = md5($password.$salt);

            //获取系统配置表里面的赠送积分  value 查询某个字段的值
            $RegisterPoint = $this->ConfigModel->where(['key' => 'RegisterPoint'])->value('value');

            //判断一下注册积分 是不是一个整数  is_numeric() 函数用于检测变量是否为数字或数字字符串。
            $RegisterPoint = is_numeric($RegisterPoint) ? abs($RegisterPoint) : 0;

            //组装数据
            $data= [
                'email' => $params['email'],
                'nickname'=>$params['nickname'],
                'password' => $password,
                'salt' => $salt,
                'point' => $RegisterPoint,
                'vip' => 0,
                'auth' => 0
            ];

            //开始插入数据库  validate 验证器  save()插入数据
            $res = $this->UserModel->validate('common/User/User')->save($data);

            // 调式sql语句
            // echo $this->UserModel->getLastSql();

            if($res === FALSE)
            {
                //注册失败
                // getError 返回操作的结果
                $this->error($this->UserModel->getError());
                exit;
            }else
            {
                //注册成功，跳转到登录界面
                $this->success('注册成功',url('home/index/login'));
                exit;
            }
         
            exit;
        }
        return $this->fetch();
    }

    // 生成验证码
    public function captcha(){
        $config =    [
            // 验证码位数
            'length'=> 4
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    // 退出
    public function logout(){

        Cookie::delete('LoginUser');

        $this->success('退出成功',url('home/index/login'));
        exit;
    }

    // 邮件点击校验
    public function email(){
        if($this->request->isGet()){
            //获取参数
            $email = $this->request->param('email', 'true');

            if(empty($email))
            {
                $this->error('验证的邮箱参数有误,请重新验证','login.php');
                exit;
            }
            //field 查询指定字段 
            $userlist = $this->UserModel->field('id,email')->select();

            $id = '';

            foreach($userlist as $item){
                //md5加密
                $emails  = md5($item['email']);
                // 邮箱加密码校验对比
                if($email == $emails){
                    $id = $item['id'];
                    break;
                }
            }

            //判断是否有找到人
            if(!$id)
            {
                $this->error('未找到需要验证的邮箱用户，请查验后重新验证');
                exit;
            }

            $data = [
                'id'=> $id,
                'auth' => 1
            ];

            $result = $this->UserModel->isUpdate()->save($data);

            if($result === FALSE)
            {
                $this->error('邮箱验证失败', url('home/user/user'));
                exit;
            }else
            {
                $this->success('邮箱验证成功', url('home/user/user'));
                exit;
            }
        }
    }

    // 帖子详情
    public function info()
    {
        // 分类ID
        $cateid = $this->request->param('cateid', 0);

        $id = $this->request->param('postid', 0);

        //查询分类列表
        $catelist = model('Post.Cate')->order('id asc')->limit(6)->select();

        // 帖子详情
        $postinfo = $this->PostModel->with(['cate','user'])->find($id);

        // 评论总数
        $count = $this->CommentModel->where(['postid' => $id])->count();
        
        //判断是否有登录
        $User = empty(Cookie::get('LoginUser')) ? [] : Cookie::get('LoginUser');
        $userid = isset($User['id']) ? $User['id'] : 0;
        $Userinfo = $this->UserModel->find($userid);

        //收藏的状态
        $CollectStatus = false;

        //访问量 字符串变成数组
        $visit = trim($postinfo['visit']);
        //转换为数组
        $VisitArr = explode(',',$visit);
        //去除数组中的空元素
        $VisitArr = array_filter($VisitArr);
        // is_array判断是否是个数组，count计算数组的长度
        $VisitCount = is_array($VisitArr) ? count($VisitArr) : 0;


        if($Userinfo){
            $collect = model('User.Collect')->where(['userid' => $userid, 'postid' => $id])->find();

            //如果查出来有，说明有收藏
            $CollectStatus = $collect ? true : false;

            //当前这个人没访问过
            if(!in_array($userid, $VisitArr)){
                $VisitArr[] = $userid;
                //implode()数组转化为字符串
                $data = [
                    'id' => $id,
                    'visit' => implode(',', $VisitArr)
                ];
                // 更新帖子访问量
                $visitupdate = $this->PostModel->isUpdate()->save($data);
            }
        }

        //查询评论
        $commentlist = $this->CommentModel->with('user')->where(['postid' => $id])->order('id', 'asc')->order('level', 'asc')->select();

        //将评论递归处理
        $commentlist = CommentTree($commentlist, 0 , $Userinfo);

        // var_dump($commentlist);
        // exit;

        $this->assign([
            'catelist' => $catelist,
            'cateid' => $cateid,
            'postinfo' =>$postinfo,
            'count' => $count,
            'CollectStatus'=>$CollectStatus,
            'VisitCount' => $VisitCount,
            'commentlist' => $commentlist
        ]);

        return $this->fetch();
    }
}
